from selenium import webdriver
import time
from PIL import Image
from selenium.webdriver import ActionChains #鼠标动作链
"""
注意事项：在裁剪验证码图片出现偏差的话，你可以调整电脑的缩放比例为100%
"""

# 指定无头浏览器
bro = webdriver.Chrome(executable_path='./chromedriver')
bro.maximize_window()
url = 'https://kyfw.12306.cn/otn/resources/login.html'
bro.get(url)
time.sleep(3)
# 点击账号登录按钮
bro.find_elements_by_class_name('login-hd-account')[0].click()
time.sleep(1)
# 输入账号和密码信息
username=bro.find_element_by_id('J-userName')
username.send_keys('wl')
pwd = bro.find_element_by_id('J-password')
pwd.send_keys('123456')
# 验证码识别,截屏
bro.save_screenshot('./main.png')  #  main.png:整个登录页面对应图片
# 验证码图片对应的img标签
img_path=bro.find_element_by_xpath('//*[@id="J-loginImg"]')
# 当前标签在页面左下角的坐标
loc =img_path.location
# 当前标签在页面中的尺寸(长宽)
size =img_path.size
# 裁剪的矩形区域(走下角和右上角坐标为裁剪区域)
rangle = (int(loc['x']),int(loc['y']),int(loc['x']+size['width']),int(loc['y']+size['height']))
i =Image.open('./main.png')
fram =i.crop(rangle)
fram.save('./code.png')  #code.png就是验证码图片


# 超级鹰识别验证码代码
import requests
from hashlib import md5
class Chaojiying_Client(object):
    def __init__(self, username, password, soft_id):
        self.username = username
        password =  password.encode('utf8')
        self.password = md5(password).hexdigest()
        self.soft_id = soft_id
        self.base_params = {
            'user': self.username,
            'pass2': self.password,
            'softid': self.soft_id,
        }
        self.headers = {
            'Connection': 'Keep-Alive',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }
    def PostPic(self, im, codetype):
        """
        im: 图片字节
        codetype: 题目类型 参考 http://www.chaojiying.com/price.html
        """
        params = {
            'codetype': codetype,
        }
        params.update(self.base_params)
        files = {'userfile': ('ccc.jpg', im)}
        r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files, headers=self.headers)
        return r.json()
    def ReportError(self, im_id):
        """
        im_id:报错题目的图片ID
        """
        params = {
            'id': im_id,
        }
        params.update(self.base_params)
        r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=params, headers=self.headers)
        return r.json()

def transform(imgpath,imgtype):
    chaojiying = Chaojiying_Client('13227187518', '13227187518', '909588')	#用户中心>>软件ID 生成一个替换 96001
    im = open(imgpath, 'rb').read()													#本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
    return chaojiying.PostPic(im, imgtype)												#1902 验证码类型  官方网站>>价格体系 3.4+版 print 后要加()

# result 返回需要点击验证码上子图的坐标  x1,y1|x2,y2|x3,y3 类型为字符串
result=transform('./code.png',9004)['pic_str']
print(result)
# 将坐标x1,y1|x2,y2|x3,y3转换成列表，点击每个坐标
all_list=[]  #[[x1,y1],[x2,y2]]
if '|'in result:
    list = result.split('|')
    for i,j in enumerate(list):
        xy_list=[]
        x=int(list[i].split(',')[0])
        y=int(list[i].split(',')[1])
        xy_list.append(x)
        xy_list.append(y)
        all_list.append(xy_list)
else:
    list = result.split(',')
    xy_list=[]
    xy_list.append(int(list[0]))
    xy_list.append(int(list[1]))
    all_list.append(xy_list)

for pos in all_list:
    x = pos[0]
    y = pos[1]
    # x,y就是每一个要点击的点的坐标 perform()立即执行
    ActionChains(bro).move_to_element_with_offset(img_path,x,y).click().perform()
    time.sleep(1)

#点击登录按钮
bro.find_element_by_id('J-login').click()
time.sleep(5)
bro.quit()

